package com.zxc.transliterate.baidu;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class TransApi {
	private static final String TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate";

//    private static String appid = "20231225001920543";
//    private static String securityKey = "ujb4vvTTJdEm7eRTsMz2";
//	private static String appid = "20231225001920790";
//	private static String securityKey = "ttk1gVIl0aRzHRfXNHtT";
	
	private static String appid = "20240613002075980";
	private static String securityKey = "3XWgs_wOKahLuTHzA2lv";

	public TransApi() {
	}

	public static String transliterate(String query,String from,String to) {
		Map<String, String> params = buildParams(query,from,to);
		String transResults = HttpGet.get(TRANS_API_HOST, params);
		JSONObject resultJSON = JSON.parseObject(transResults);
		JSONArray tansResult = resultJSON.getJSONArray("trans_result");
		String trans = query;
		if (tansResult != null) {
			for (Object json : tansResult) {
				if (json != null) {
					trans = (String) ((JSONObject) json).get("dst");
					System.out.println("转换文字：[" + query + "]>>>>" + trans);
					break;
				}
			}
		} else if (resultJSON.get("error_code") != null) {
			System.out.println("转换错误，原因：" + resultJSON.get("error_code") + "," + resultJSON.get("error_msg"));
		}
		return trans;
	}
	
	public static String transliterate(String query,String to) {
		Map<String, String> params = buildParams(query,"zh",to);
		String transResults = HttpGet.get(TRANS_API_HOST, params);
		JSONObject resultJSON = JSON.parseObject(transResults);
		JSONArray tansResult = resultJSON.getJSONArray("trans_result");
		String trans = query;
		if (tansResult != null) {
			for (Object json : tansResult) {
				if (json != null) {
					trans = (String) ((JSONObject) json).get("dst");
					System.out.println("转换文字：[" + query + "]>>>>" + trans);
					break;
				}
			}
		} else if (resultJSON.get("error_code") != null) {
			System.out.println("转换错误，原因：" + resultJSON.get("error_code") + "," + resultJSON.get("error_msg"));
		}
		return trans;
	}

	private static Map<String, String> buildParams(String query,String from,String to) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("q", query);
		params.put("from", from);
		// to "jp"
		params.put("to", to);

		params.put("appid", appid);

		// 随机数
		String salt = String.valueOf(System.currentTimeMillis());
		params.put("salt", salt);

		// 签名
		String src = appid + query + salt + securityKey; // 加密前的原文
		params.put("sign", MD5.md5(src));

		return params;
	}

	
	public static void main(String[] args) {
		System.out.println(transliterate("机场","cht"));
	}
}
